﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;

public partial class TEST : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      
   
        //----上面已經事先寫好 Using System.Web.Configuration ----
        //---- (連結資料庫)----
        SqlConnection Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);
        Conn.Open();

        SqlDataReader dr = null;
        SqlCommand cmd = new SqlCommand("select user_username, user_password from [user] where user_username = @UserName and user_password = @Userpassword", Conn);

        cmd.Parameters.AddWithValue("@UserName", TextBox1.Text);
        cmd.Parameters.AddWithValue("@Userpassword", TextBox2.Text);
        dr = cmd.ExecuteReader();   //---- 這時候執行SQL指令，取出資料

        //實作記住我功能
        

        if (!dr.Read())
        {
            Response.Write("帳號或是密碼有錯！");

            cmd.Cancel();
            //----關閉DataReader之前，一定要先「取消」SqlCommand
            dr.Close();
            Conn.Close();
            Conn.Dispose();

            Response.End();   //--程式暫停。或是寫成 return，脫離這個事件。
        }
        else
        {
            
            Session["Login"] = "OK";
            //--帳號密碼驗證成功，才能獲得這個 Session["Login"] = "OK" 鑰匙


            //將連線資訊存在Cookie裡
            //Session["u_name"] = dr["user_username"].ToString();
            //紀錄紀住我選項
            FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, CheckBoxRemeber.Checked);
            //Session["u_passwd"] = dr["user_password"].ToString();
 
            //將帳號資訊存在Cookie裡並保存七天
            Response.Cookies["u_name"].Value = dr["user_username"].ToString();
            //Response.Cookies["u_passwd"].Value = dr["user_password"].ToString();
            Response.Cookies["u_name"].Expires = DateTime.Now.AddDays(7);
            //Response.Cookies["u_passwd"].Expires = DateTime.Now.AddDays(7);

           
           
           // string groups = "Admin";

           // bool isCookiePersistent = CheckBoxRemeber.Checked;



           // FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, TextBox1.Text,
           //                                        DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);

           // //字串加密
           // String encryptedTicket = FormsAuthentication.Encrypt(authTicket);

           // HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

           // if (true == isCookiePersistent)
           //     authCookie.Expires = authTicket.Expiration;    // cookie過期日

           // //Add the cookie to the outgoing cookies collection.
           // Response.Cookies.Add(authCookie);


           // //通過身份驗證的人，才能看見原本的網頁，例如Hello.aspx。
           // //通過驗證後，自動回到（導向）原本想看的網頁。
           //Response.Redirect(FormsAuthentication.GetRedirectUrl(TextBox1.Text, false));


            cmd.Cancel();
            dr.Close();
            Conn.Close();
            Conn.Dispose();
           
            Response.Redirect("https://www.google.com.tw/");
            //--帳號密碼驗證成功，導向另一個網頁。
        }


    }
    protected void Button2_Click(object sender, EventArgs e)
    {
  
    }
    protected void CheckBoxRemeber_CheckedChanged(object sender, EventArgs e)
    {

    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Acccount.aspx");
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        Response.Redirect("https://www.google.com.tw/");
    }
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        SqlConnection Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);
        SqlDataReader dr = null;
        SqlCommand cmd = new SqlCommand("select user_email,user_password from [user] where user_username = @UserName", Conn);
        cmd.Parameters.AddWithValue("@UserName", TextBox1.Text);

        try
        {
            Conn.Open();//連接DB
            dr = cmd.ExecuteReader();//取出資料
            if (dr.HasRows)
            {   
                
                //MailMessage uMail = new MailMessage("sdfsonic@yahoo.com.tw", dr["user_email"].ToString(), "你的密碼", "你的密碼是:" + dr["user_password"].ToString());
                //SmtpClient mailClient = new SmtpClient("125.227.255.80");
                //mailClient.Send(uMail);
                //mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;


                dr.Read();


                SmtpClient MySmtp = new SmtpClient("smtp.gmail.com", 587);
                //開啟Gmail連線
                //設定你的帳號密碼
               MySmtp.Credentials = new System.Net.NetworkCredential("sdfsonic", "c0520113");
 
               //Gmial 的 smtp 必需要使用 SSL
               MySmtp.EnableSsl = true;
 
               //發送Email
               MySmtp.Send("sdfsonic@gmail.com", dr["user_email"].ToString(), "你的密碼", "你的密碼是:" + dr["user_password"].ToString()); 
               MySmtp.Dispose();
           
            }
            else
            {
                Response.Write("錯誤");

            }
            cmd.Cancel();
            dr.Close();
            Conn.Close();
            Conn.Dispose();

        }
        catch (Exception ex)
        {
            Response.Write("Error Message--" + ex.ToString());

        }
    }
}
